import router from '@/router'
import { ElMessage } from "element-plus";
import axios, { Axios, AxiosError} from 'axios'

const axiosInstance = axios.create({
  baseURL: '/api',
  timeout: 5000
})

axiosInstance.interceptors.request.use((config: any) => {
  let token = JSON.parse(localStorage.getItem('USERINFO') || '{}');
  // if (!token) {
  //   router.push('/login')
  //   return config
  // }
  // http://localhost:5175/api/hosp/hospital/1/10?hostype=&districtCode=
  // http://localhost:5174/api/hosp/hospital/1/10?hostype=&districtCode=
  config.headers = {
    ...config.headers,
    token: token.token || ''
  }
  // config.headers.Authorization = token || ''
  return config
},
(error: AxiosError) => {
  Promise.reject(error)
}
)

axiosInstance.interceptors.response.use(
  (res) => {
    if (res.status === 200) {
      return res.data
    }
  },
  (err: AxiosError) => {
    const status = err.response?.status
    switch (status) {
      case 404:
        //错误提示信息
        ElMessage({
          type: 'error',
          message: '请求失败路径出现问题'
        })
        break;
      case 500:
        //错误提示信息
        ElMessage({
          type: 'error',
          message: '服务器内部错误'
        })
        break;
      case 503:
        //错误提示信息
        ElMessage({
          type: 'error',
          message: '服务器当前不可用'
        })
        break;
      case 401:
        //错误提示信息
        ElMessage({
          type: 'error',
          message: '参数有误'
        })
        break;
      default:
        break;
    }
  }
)

//对外暴露axios
export default axiosInstance;
